package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.constants.message.ArticleVisitStreamMess;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    AdminFeign adminFeign;


    /**
     * 重新计算文章热度  更新redis缓存
     * @param mess
     */
    @Override
    public void updateApArticle(ArticleVisitStreamMess mess) {

        //1 根据文章的id查询文章
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2 修改文章的行为数据（阅读1、点赞3、评论5、收藏8）
        if (mess.getView() != 0) {
            int view = (int) (apArticle.getViews() == null ? mess.getView() : mess.getView() + apArticle.getViews());
            apArticle.setViews(view);
        }
        if (mess.getLike() != 0) {
            int like = (int) (apArticle.getLikes() == null ? mess.getLike() : mess.getLike() + apArticle.getLikes());
            apArticle.setLikes(like);
        }
        if (mess.getComment() != 0) {
            int comment = (int) (apArticle.getComment() == null ? mess.getComment() : mess.getComment() + apArticle.getComment());
            apArticle.setComment(comment);
        }
        if (mess.getCollect() != 0) {
            int collection = (int) (apArticle.getCollection() == null ? mess.getCollect() : mess.getCollect() + apArticle.getCollection());
            apArticle.setCollection(collection);
        }
        apArticleMapper.updateById(apArticle);

        //3 计算分数
        Integer score =computeScore(apArticle);
        //3.1 当天文章分数 * 3
        String pdate = DateUtils.dateToString(apArticle.getPublishTime());
        String cdate = DateUtils.dateToString(new Date());
        if (pdate.equals(cdate)) {
            score = score * 3;
        }

        //4 更新redis各个频道下的缓存数据
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+apArticle.getChannelId());

        //5 更新redis推荐频道下的缓存数据
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 更新文章的缓存
     * @param apArticle
     * @param score
     * @param cachekey
     */
    private void updateArticleCache(ApArticle apArticle, Integer score, String cachekey) {
        //1 如果当前缓存中有当前文章，更新分值
        String hotArticleListJson = (String) redisTemplate.opsForValue().get(cachekey);
        boolean flag = false;
        if (StringUtils.isNotBlank(hotArticleListJson)) {
            // 转成集合
            List<HotArticleVo> hotArticleVos = JSON.parseArray(hotArticleListJson, HotArticleVo.class);

            for (HotArticleVo hotArticleVo : hotArticleVos) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = true;
                    break;
                }
            }
            //2 如果没有则新增到redis
            if (!flag) {
                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hotArticleVo);
                hotArticleVo.setScore(score);
                hotArticleVos.add(hotArticleVo);
            }

            //3 更新缓存（排序+前30条）
            sortAndCache(hotArticleVos, cachekey);
        }
    }

    @Override
    public void computeHotArticle() {
        //1 查询前5天的所有文章
        String date = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));
        List<ApArticle> articleList = apArticleMapper.selectArticleByDate(date);

        //2 计算文章分值
       List<HotArticleVo> hotArticleVos =  computeArticleScore(articleList);

        //3 缓存热点文章数据到Redis
        cacheTagToRedis(hotArticleVos);
    }

    /**
     * 缓存热点文章数据到Redis
     * 1、各个频道下的列表（30条）
     * 2、推荐的文章列表（全部文章分数排序的前30条）
     * @param hotArticleVos
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {
        //1 各个频道下的列表（30条）
        ResponseResult result = adminFeign.findAll();
        if (result != null && result.getCode() == 0) {
            List<AdChannel> channelList = JSON.parseArray(JSON.toJSONString(result.getData()), AdChannel.class);

            channelList.forEach(adChannel -> {
               List<HotArticleVo> hotArticleVoList = hotArticleVos.stream()
                                                        .filter( hotArticleVo ->  adChannel.getId().equals( hotArticleVo.getChannelId() ))
                                                        .collect(Collectors.toList());

                sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
            });

        }
        //2 推荐的文章列表 __all__ 推荐的tag对应key
        sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 文章列表缓存到redis中，需要排序取30条
     * @param hotArticleVoList
     * @param cachekey
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVoList, String cachekey) {

        hotArticleVoList = hotArticleVoList.stream()
                                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                                .limit(30)
                                .collect(Collectors.toList());

        redisTemplate.opsForValue().set(cachekey, JSON.toJSONString(hotArticleVoList));
    }

    /**
     * 2 计算文章的分值
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {

        return  articleList.stream()
                .map(apArticle -> {
                    HotArticleVo hotArticleVo = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hotArticleVo);

                    //2.1 处理每一篇文章分数
                    Integer score =computeScore(apArticle);
                    hotArticleVo.setScore(score);
                    return hotArticleVo;
                })
                .collect(Collectors.toList());
    }

    /**
     * 2.1 处理每一篇文章分数
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        int score = 0;

        // 阅读 1
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        // 点赞 3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 评论 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
